package com.vonchenchen.photodemo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.vonchenchen.photodemo.utils.BlurUtil;
import com.vonchenchen.photodemo.utils.ImageLoaderManager;
import com.vonchenchen.photodemo.utils.ImageUtils;
import com.vonchenchen.photodemo.utils.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MainActivity extends Activity {

    private Button mPickBtn;
    private Button mTakeBtn;

    //拍照相关
    private final static int CROP = 200;



    String mSaveBitmapPath = ImageLoaderManager.FILE_SAVEPATH;

    private Uri origUri;
    private File protraitFile;
    private Bitmap protraitBitmap;
    private String protraitPath;

    private String theLarge;
    private ImageView mImageView;
    private Uri protraitUri;
    private Button mLoadBtn;
    private Button mClearBtn;
    private Button mLoadNetBtn;

    DisplayImageOptions options = new DisplayImageOptions.Builder()
        .cacheInMemory(true)    //使用内存  默认不使用
        .cacheOnDisk(true)      //使用硬盘  默认不使用
            .build();

    DisplayImageOptions optionsUseMemory = new DisplayImageOptions.Builder()
            .cacheInMemory(true)    //使用内存  默认使用
            .cacheOnDisk(false)      //使用硬盘  默认不使用
            .build();

    DisplayImageOptions optionsUseDisk = new DisplayImageOptions.Builder()
            .cacheInMemory(false)    //使用内存  默认不使用
            .cacheOnDisk(true)      //使用硬盘  默认使用
            .build();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPickBtn = (Button) findViewById(R.id.btn_pick);
        mTakeBtn = (Button) findViewById(R.id.btn_take);
        mLoadBtn = (Button) findViewById(R.id.btn_load);
        mLoadNetBtn = (Button) findViewById(R.id.btn_load_net);
        mClearBtn = (Button) findViewById(R.id.btn_clear);

        mImageView = (ImageView) findViewById(R.id.iv_photo);

        //选择图片
        mPickBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startImagePick();
            }
        });

        //拍照
        mTakeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startTakePhoto();
            }
        });

        //ImageLoader管理本地图片
        mLoadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                //指定要获取照片的名字字段
//                String name = "test";
//                //构造指定图片的文件uri
//                File file;
//                file = new File(ImageLoaderManager.FILE_SAVEPATH_FUZZY + name +".jpg");
//                Uri uri = Uri.fromFile(file);
//                String uriStr = uri.toString();
//
//                //从本地文件夹获取，不使用硬盘缓存，不使用内存缓存
//                ImageLoader.getInstance().displayImage(uriStr, mImageView);

                ImageLoaderManager.loadBlurImage(protraitPath, "test1", mImageView, null);
            }
        });

        //ImageLoader下载网络图片，并拷贝到本地路径，方便进一步使用
        mLoadNetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String uriStr = "http://img.my.csdn.net/uploads/201508/05/1438760724_9463.jpg";

                ImageLoader.getInstance().displayImage(uriStr, mImageView, options, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String s, View view) {
                    }
                    @Override
                    public void onLoadingFailed(String s, View view, FailReason failReason) {
                    }
                    @Override
                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                        //如果需要使用图片，下载完毕后拷贝到我们路径
                        String path = ImageLoaderManager.saveImageInOurDocument(uriStr, "upload");
                        if(path != null){
                            ImageLoader.getInstance().displayImage(path, mImageView, options);
                        }
                    }
                    @Override
                    public void onLoadingCancelled(String s, View view) {
                    }
                });
            }
        });

        //清空ImageView
        mClearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mImageView.setImageResource(R.mipmap.ic_launcher);
            }
        });
    }

    /**
     * Activity返回结果
     * @param requestCode
     * @param resultCode
     * @param imageReturnIntent
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnIntent) {

        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA: //开启拍照

                //origUri 是我们指定的拍照完毕后存储的uri
                startActionCrop(origUri);                        // 拍照后裁剪
                break;
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:   //开启选取本地图片
                if(imageReturnIntent != null) {
                    //我们选择完图片后返回其Uri
                    startActionCrop(imageReturnIntent.getData());// 选图后裁剪
                }
                break;
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:  //开启图片剪裁

                boolean b = protraitFile.exists();
                if (!StringUtils.isEmpty(protraitPath) && protraitFile.exists()) {
                    //**************************************图片处理与保存*********************************************************

//                    //解压图片
//                    protraitBitmap = ImageUtils.convertToBitmap(protraitPath, 200, 200);
//                    //将位图进行处理
//                    protraitBitmap = BlurUtil.blurBitmap(protraitBitmap, MainActivity.this);
//                    //将处理结果压缩为名字为 test.jpg的 jpeg格式文件，写入指定文件
//                    protraitUri = ImageLoaderManager.saveCroppedImage(protraitBitmap, "test");
//                    //用ImageLoader加载这个文件
//                    ImageLoader.getInstance().displayImage(protraitUri.toString(), mImageView);

                    ImageLoaderManager.loadBlurImage(protraitPath, "test1", mImageView, null);
                }
                break;
        }
    }

    //***********************************************************************
    /**
     * 选择图片
     */
    private void startImagePick() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
        } else {
            //ACTION_PICK 可以显示详细的选择样式
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
        }
    }

    /**
     * 拍照
     */
    private void startTakePhoto() {
        Intent intent;
        // 判断是否挂载了SD卡
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = ImageLoaderManager.FILE_SAVEPATH_CAMERA;
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (StringUtils.isEmpty(savePath)) {
            Toast.makeText(this, "无法保存照片，请检查SD卡是否挂载", Toast.LENGTH_SHORT);
            return;
        }

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String fileName = ImageLoaderManager.FILE_SAVENAME_CAMERA + timeStamp + ".jpg";// 照片命名
        File out = new File(savePath, fileName);
        Uri uri = Uri.fromFile(out);
        origUri = uri;

        theLarge = savePath + fileName;// 该照片的绝对路径

        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent,
                ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
    }

    /**
     * 拍照后裁剪
     * @param data 原始图片Uri
     */
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //data 这个uri必须经过new File出来
        intent.setDataAndType(data, "image/*");
        //指定裁剪后的图片的保存路径
        intent.putExtra("output", getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", CROP);// 输出图片大小
        intent.putExtra("outputY", CROP);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        startActivityForResult(intent,
                ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
    }

    /**
     * 在指定裁剪
     * @param uri
     * @return
     */
    private Uri getUploadTempFile(Uri uri) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(ImageLoaderManager.FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            Toast.makeText(this, "无法保存上传的头像，请检查SD卡是否挂载", Toast.LENGTH_SHORT).show();
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());

        //将uri转换为绝对路径,  如果是file:// 开头的uri，获取路径
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

        // 如果是标准Uri
        if (StringUtils.isEmpty(thePath)) {
            //将uri转换为绝对路径,  如果是content:// 开头的uri，获取路径
            thePath = ImageUtils.getAbsoluteImagePath(this, uri);
        }
        String ext = StringUtils.getFileFormat(thePath);
        ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
        // 裁剪完毕的照片命名
        String cropFileName = ImageLoaderManager.FILE_SAVENAME_CROP + timeStamp + "." + ext;
        // 裁剪头像的绝对路径
        protraitPath = ImageLoaderManager.FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);

        Uri cropUri = Uri.fromFile(protraitFile);

        protraitUri = cropUri;

        return cropUri;
    }
}
